package com.phonebook.controller;

import com.phonebook.constant.JwtConstant;
import com.phonebook.entity.Admin;
import com.phonebook.entity.ResponseResult;
import com.phonebook.service.AdminService;
import com.phonebook.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 登陆controller
 *
 * @author 高旭
 * @date 2021-04-24
 */
@RestController
@RequestMapping("/")
@Api(tags = "登陆Api")
public class LoginController {

    private final AdminService adminService;

    @Autowired
    public LoginController(AdminService adminService) {
        this.adminService = adminService;
    }

    /**
     * 管理员登录
     *
     * @return
     */
    @ApiOperation("登录")
    @ApiImplicitParam(name = "admin", value = "管理员", dataTypeClass = Admin.class, required = true)
    @PostMapping("/login")
    public ResponseResult login(@RequestBody Admin admin) {
        Admin u = adminService.login(admin);
        if (u == null) {
            return ResponseResult.error("用户名或者密码错误");
        }
        return ResponseResult.success("登陆成功！").put("token", JwtUtils.createJWT(String.valueOf(u.getId()), u.getUserName(), JwtConstant.JWT_TTL));
    }

}
